package com.wrt.sps.mgt.service.impl;

import java.util.List;
import java.util.Optional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wrt.sps.mgt.dao.RoleDao;
import com.wrt.sps.mgt.dao.UserDao;
import com.wrt.sps.mgt.entity.Role;
import com.wrt.sps.mgt.entity.User;
import com.wrt.sps.mgt.pojo.RoleDTO;
import com.wrt.sps.mgt.service.PermissionService;
import com.wrt.sps.mgt.service.RoleService;

/**
 * 角色服务实现层
 * 
 * @author 文瑞涛
 * @date 2021年1月7日 下午12:01:11
 */
@Service
public class RoleServiceImpl implements RoleService {

	@Resource
	private PermissionService permissionService;
	@Resource
	private RoleDao roleDao;
	@Resource
	private UserDao userDao;

	@Override
	@PostConstruct
	@Transactional(rollbackFor = Exception.class)
	public void initAdminRole() {
		Role adminRole = new Role();
		adminRole.createAdminRole();
		Role savedRole = findRoleByExample(adminRole);
		if (null == savedRole) {
			adminRole.setPermissions(permissionService.getAllPermissions());
			roleDao.save(adminRole);
		} else {
			savedRole.setPermissions(permissionService.getAllPermissions());
			roleDao.save(savedRole);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public Role findRoleByExample(Role role) {
		Optional<Role> tempRole = roleDao.findOne(Example.of(role));
		Role result = null;
		if (tempRole.isPresent()) {
			result = tempRole.get();
		}
		return result;
	}

	@Override
	@Transactional(readOnly = true)
	public boolean checkRoleExistByExample(String rName) {
		Role role = new Role();
		role.setRoleName(rName);
		return roleDao.exists(Example.of(role));
	}

	@Override
	@Transactional(readOnly = true)
	public Role findRoleById(Long id) {
		Role result = null;
		Optional<Role> tempRole = roleDao.findById(id);
		if (tempRole.isPresent()) {
			result = tempRole.get();
		}
		return result;
	}

	@Override
	@Transactional(readOnly = true)
	public Page<Role> query(String rName, int page, int limit) {
		Pageable pageable = PageRequest.of(page, limit, Sort.by(Sort.Direction.DESC, "createdDate", "id"));
		Role queryRole = new Role();
		queryRole.setRoleName(rName);
		ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("roleName",
				match -> match.contains().ignoreCase());
		return roleDao.findAll(Example.of(queryRole, matcher), pageable);
	}

	@Override
	@Transactional(readOnly = true)
	public List<Role> getAllRoles() {
		return roleDao.findAll();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Role saveRole(RoleDTO dto) {
		Role saveRole = null;
		if (null != dto.getKey() && 0 != dto.getKey()) {
			Optional<Role> temp = roleDao.findById(dto.getKey());
			if (temp.isPresent()) {
				saveRole = temp.get();
			} else {
				return null;
			}
		} else {
			saveRole = new Role();
			saveRole.setRoleName(dto.getRoleName());
		}
		Long[] permissionIds = dto.getPermissionIds();
		if (null != permissionIds && permissionIds.length > 0) {
			saveRole.setPermissions(permissionService.findPermissionsByIds(permissionIds));
		} else {
			saveRole.setPermissions(null);
		}
		return roleDao.save(saveRole);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(Long id) {
		Optional<Role> tempRole = roleDao.findById(id);
		if (tempRole.isPresent()) {
			Role temp = tempRole.get();
			List<User> users = userDao.findUserByRole(temp);
			for (User u : users) {
				u.setRole(null);
				userDao.save(u);
			}
			temp.setPermissions(null);
			roleDao.save(temp);
			roleDao.deleteById(temp.getId());
		}
	}

}
